package com.zhuanzhuan.hero.user.service.impl;

import com.zhuanzhuan.hero.user.entity.HeroUserInfo;
import com.zhuanzhuan.hero.user.enums.ExceptionMsgEnum;
import com.zhuanzhuan.hero.user.exception.BusinessException;
import com.zhuanzhuan.hero.user.helper.PushHelper;
import com.zhuanzhuan.hero.user.service.HeroUserInfoService;
import com.zhuanzhuan.hero.user.service.IPushService;
import com.zhuanzhuan.hero.user.util.AsyncUtil;
import com.zhuanzhuan.hero.user.util.RetryUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @ClassName PushServiceImpl
 * @Description
 * @Author hanjunjun
 * @Date 2024/8/1 10:31
 */
@Service
@Slf4j
public class PushServiceImpl implements IPushService {

    @Resource
    private PushHelper pushHelper;

    @Resource
    private HeroUserInfoService heroUserInfoService;

    @Override
    public void reliableSendPush(Long fromUid, Long toUid) {
        if (Objects.isNull(fromUid) || Objects.isNull(toUid)) {
            return;
        }
        HeroUserInfo fromUser = heroUserInfoService.getUserByUid(fromUid);
        if (Objects.isNull(fromUser)) {
            return;
        }

        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("nickname", fromUser.getNickname());
        this.sendPushAsync(toUid, PushHelper.RELIABLE_AUTH_TEMPLATE_ID, paramMap);
    }

    @Override
    public void fraternithSendPush(Long fromUid, Long toUid) {
        if (Objects.isNull(fromUid) || Objects.isNull(toUid)) {
            return;
        }
        HeroUserInfo fromUser = heroUserInfoService.getUserByUid(fromUid);
        if (Objects.isNull(fromUser)) {
            return;
        }

        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("nickname", fromUser.getNickname());
        this.sendPushAsync(toUid, PushHelper.FRATERNITY_AUTH_TEMPLATE_ID, paramMap);
    }

    @Override
    public void sendPushAsync(Long receiverId, Integer templateId, Map<String, String> paramMap) {
        if (Objects.isNull(receiverId) || Objects.isNull(templateId)) {
            throw new BusinessException(ExceptionMsgEnum.PARAM_ERROR);
        }
        AsyncUtil.run(() -> {
            RetryUtil.retryRunableNoInterval(() -> {
                pushHelper.sendPush(receiverId, templateId, paramMap);
            });
        });
    }
}
